using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using Cinemachine;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    public static CameraController Instance;
    private CinemachineVirtualCamera virtualCamera;
    private Coroutine shifter;                                                  //记录现在应该lerp的摄像机size，更新corotine
    [SerializeField] private List<cameraShifter> cameraShifterList;

    private void Awake()
    {
        Instance = this;
        virtualCamera = GetComponent<CinemachineVirtualCamera>();
    }

    private void Start()
    {
        
    }

    private IEnumerator SetCameraSize(float size)
    {
        print(size);
        while (Mathf.Abs(virtualCamera.m_Lens.OrthographicSize - size) > 0.01f)
        {
            virtualCamera.m_Lens.OrthographicSize = Mathf.Lerp(virtualCamera.m_Lens.OrthographicSize,size,Time.deltaTime);
            yield return null;
        }
        
        
    }

    public void ShiftCameraSize(Collider2D collider2D)
    {
        foreach (var cs in cameraShifterList)
        {
            if (collider2D == cs.collider2D)
            {
                if(shifter!=null)
                    StopCoroutine(shifter);
                shifter = StartCoroutine(SetCameraSize(cs.size));
            }
        }
    }

    private void Update()
    {
        
    }

    private void DrawCameraField(Vector3 center, float size)
    {
        center += new Vector3(0, 1, -2);
        Vector3 leftUp = center - new Vector3(size * 1.75f, -1f * size , 0);
        Vector3 rightUp = center + new Vector3(size * 1.75f, 1f * size, 0);
        Vector3 leftDown = center - new Vector3(size * 1.75f, 1f * size, 0);
        Vector3 rightDown = center + new Vector3(size * 1.75f, -1f * size, 0);
        
        Gizmos.DrawLine(leftUp,leftDown);
        Gizmos.DrawLine(leftUp,rightUp);
        Gizmos.DrawLine(rightUp,rightDown);
        Gizmos.DrawLine(rightDown,leftDown);
    }

    private void OnDrawGizmos()
    {
        foreach (var cameraShifter in cameraShifterList)
        {
            DrawCameraField(cameraShifter.collider2D.bounds.center,cameraShifter.size);
        }
    }
}

[Serializable]
public class cameraShifter
{
    public Collider2D collider2D;
    public float size;

    public cameraShifter(Collider2D collider2D, float size)
    {
        this.collider2D = collider2D;
        this.size = size;
    }
}

